/*
* backendJackd.c - LoginState Stuff
* Copyright 2006-2008 OpenWii (admin@openwii.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* Extra credits go to Bell (YAOSM) for providing the sector patching
*
* Version 2.4 by Andii
*/

#include "mn10200-wii.h"

void doStuff(void);

// Put this at the beginning of the file by using the start symbol
asm("start:
	jsr _doStuff
	jmp _beJackRetAddr
");

// This is called at loginstate 0x7f
void doStuff(void)
{
	// check if backup disc
	if (mediaFlagL <= 0x18)
	{
		unsigned long int maxSectors;

		// set media flags and emu flag
		emuFlag = 0x04;
		mediaFlagL = 0x28;

		// Single layer always has maxSectorsRaw19 as zeroes (this check allows us to differentiate DVD-RW/+RW from DVD+DL (without bitsetting)
		if (maxSectorsRaw19[0])
		{
			// Setup mediaflag for dual layer (Just setting low byte 0x28 will result in 0x2028 for DVD+DL but bit 8 and 10 needs to be set for DL)
			mediaFlagH = 0x8d;
			// Hard code last sector to 0x3F69BF to make SSBB happy even with DVD-DL discs
			maxSectors = 0x003f69bf;
			// Read and reverse max sectors for first layer on dual layer discs
			((unsigned char*)&firstLayer1)[0] = maxSectorsRaw19[2];
			((unsigned char*)&firstLayer1)[1] = maxSectorsRaw19[1];
			((unsigned char*)&firstLayer1)[2] = maxSectorsRaw19[0] - 3;		// Convert "raw" to "real" sectors
		}
		else
		{
			// Setup mediaflag for single layer
			mediaFlagH = 0x88;
			// Hard code last sector to 0x23047F to make SMG happy
			maxSectors = 0x0023047f;
			// Last sector on first layer = last sector on disc
			firstLayer1 = maxSectors;
		}
		// Last sector on first layer
		firstLayer2 = firstLayer1;

		// Last sector on disc
		wholeDisc1 = maxSectors;
		wholeDisc2 = maxSectors;

		backup = 1;		// set backup flag so we know to continue changing media flags later on
	}
	else
	{
		backup = 0;
	}

	stackRetAddr = &startBigLoop;	// go ahead and jack the return address of main loop now plz
}
